import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/LoginView.vue"),
  },
  {
    path: "/register",
    name: "register",
    component: () =>
      import(/* webpackChunkName: "register" */ "../views/RegisterView.vue"),
  },
  {
    path: "/article/detail/:id",
    name: "article",
    component: () => import("../views/article/ArticleDetail.vue"),
  },
  {
    path: "/article/add",
    name: "articleAdd",
    component: () => import("../views/article/CreateArticle.vue"),
    meta: { requiresAuth: true },
  },
  {
    path: "/article/edit/:id",
    name: "article",
    component: () => import("../views/article/EditorArticle.vue"),
    meta: { requiresAuth: true },
  },
  {
    path: "/my/home",
    name: "myHome",
    component: () => import("../views/user/UserHome.vue"),
    meta: { requiresAuth: true },
  },
  {
    path: "/my/article",
    name: "myArticle",
    component: () => import("../views/user/UserArticle.vue"),
    meta: { requiresAuth: true },
  },
  {
    path: "/my/setting",
    name: "mySetting",
    component: () => import("../views/user/UserSetting.vue"),
    meta: { requiresAuth: true },
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => {
    // Ignore "NavigationDuplicated" error
    if (err.name === "NavigationDuplicated") return;
    // Rethrow other errors
    throw err;
  });
};
// 新增路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem("token");
  console.log(isAuthenticated);

  // 需要认证的路由
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({
        path: "/login",
        query: { redirect: to.fullPath },
      });
    } else {
      next();
    }
  }
  // 已登录用户访问登录/注册页
  else if (["/login", "/register"].includes(to.path) && isAuthenticated) {
    next("/");
  } else {
    next();
  }
});

export default router;
